package com.zyk.attach;

import java.io.File;
import java.util.List;
import java.util.Scanner;

public class AttachLauncher {

    public static void printVMList(List<VM.VMDescriptor> vmList) throws Exception {
        System.out.println("\t(pid)\t(name)");
        for (VM.VMDescriptor vmDescriptor : vmList) {
            System.out.printf("\t%s\t%s\n", vmDescriptor.getPid(), vmDescriptor.getName());
        }
    }

    public static void select(File agentFile) throws Exception {
        System.out.println("====================================");
        System.out.println("外部jvm进程: ");
        List<VM.VMDescriptor> vmList = VM.getExternalVMList();
        printVMList(vmList);
        System.out.println("请输入要attach的进程id(r for refresh/q for exit): ");
        Scanner scan = new Scanner(System.in);
        String input = scan.nextLine();
        switch (input) {
            case "r":
            case "R":
                select(agentFile);
                return;
            case "Q":
            case "q":
                System.exit(0);
            default:
                boolean flag = false;
                System.out.println("请输入要附加的参数: ");
                String args = scan.nextLine();
                for (VM.VMDescriptor descriptor : vmList) {
                    if (descriptor.getPid().equals(input)) {
                        VM.attachVM(agentFile, descriptor.getPid(), args);
                        flag = true;
                        break;
                    }
                }
                if (flag) {
                    System.out.printf("代理目标进程: %s，使用代理文件: %s，成功!\n", input, agentFile.getName());
                } else {
                    System.out.println("无效pid, 请检查你的输入，或是目标进程已关闭！");
                    select(agentFile);
                }
        }
    }
}
